package restfuljobs

import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import groovyx.net.http.Method
import groovy.util.slurpersupport.NodeChild
import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH

class AbstractRestController {

    def httpBuilder = new HTTPBuilder( "$CH.config.grails.serverURL/api/" )
	def rootPath = "$CH.config.grails.serverURL/api/"
	def path
	
    def save() {
	
		def xmlBuilder = paramsToXML(params)
		
		println xmlBuilder
		
		def userId = 0
		
		if (session.user) {
			userId = session.user.id
		}
		
		httpBuilder.request(Method.POST, "application/xml"){ req ->
			headers.accept = "application/xml"
			uri.path = path
			uri.query = [userId: userId]
			body = xmlBuilder.toString()
		
			response.success = {resp, xml ->
			   println xml.attributes()['id']
			   redirect(action: "show", id: xml.attributes()['id'])
			}
			
			response.failure = { resp, xml ->
                              
               if (xml) {
               		flash.message = xml
               } else {
               		flash.message = "Error creating " + path.capitalize()
               }
                             
               if (path == "jobApplication") {               
               		render(view: "create", model: [jobApplicationInstance: new JobApplication(params)])
               		return
               } else if (path == "jobListing") {               
               		render(view: "create", model: [jobListingInstance: new JobListing(params)])
               		return
               }
               
               render(view: "create");
               return
			}
		}
		
    }	
    
    def update() {
		
        def xmlBuilder = paramsToXML(params)
		
		def userId = 0
		
		if (session.user) {
			userId = session.user.id
		}
		
		httpBuilder.request(Method.PUT, "application/xml"){ req ->
			headers.accept = "application/xml"
			uri.path = path + "/$params.id"
			uri.query = [userId: userId]
			body = xmlBuilder.toString()
		
			response.success = {resp, xml ->			   
			   redirect(action: "show", id: xml.attributes()['id'])
			}
			
			response.failure = { resp ->
				flash.message = message(code: 'default.not.found.message', args: [message(code: path+".label", default: path.capitalize()), params.id])
				redirect(action: "list")
				return				
			}
		}
			        
    }
    
    def delete() {
        
		httpBuilder.request(Method.DELETE, "application/xml"){ req ->
			headers.accept = "application/xml"
			uri.path = path + "/$params.id"			
		
			response.success = {resp, xml ->
			   flash.message = message(code: 'default.deleted.message', args: [message(code: path+".label", default: path.capitalize()), params.id])
			   redirect(action: "list")
			}
			
			response.failure = { resp ->
				flash.message = message(code: 'default.not.found.message', args: [message(code: path+".label", default: path.capitalize()), params.id])
				redirect(action: "list")
				return				
			}
		}        
    }
	
	protected StringBuilder paramsToXML(def params) {
		StringBuilder xmlBuilder = new StringBuilder("<" + path.capitalize())
		if (params.id) {
			xmlBuilder.append(" id='$params.id' ")
		}
		xmlBuilder.append( ">")
		params.each {
			def key = it.key
			if (it.value instanceof String) {
				xmlBuilder.append("<" + key + ">")
				xmlBuilder.append("<![CDATA[" + it.value + "]]>")
				xmlBuilder.append("</" + key + ">")
			} else {
			    if (it.value['id']) {					
			    	xmlBuilder.append("<" + it.key + " id='" + it.value['id'] + "'/>")
				}
			}
			
		}
		xmlBuilder.append("</" + path.capitalize() + ">");
		return xmlBuilder
	}         
}